import 'package:fishing/providers/user_provider.dart';
import 'package:fishing/widgets/version_update_listener.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class MainScaffold extends StatefulWidget {
  final Widget child;
  const MainScaffold({super.key, required this.child});
  @override
  State<MainScaffold> createState() => _MainScaffold();
}

class _MainScaffold extends State<MainScaffold> {
  @override
  void initState() {
    super.initState();
  }

  List<String> tabs = ['/home', '/fishing', '/community', '/profile'];

  List<IconData> icons = [];

  int _locationToIndex(String location) {
    final index = tabs.indexWhere((path) => location.startsWith(path));
    return index < 0 ? 0 : index;
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<UserProvider>(context);
    if (provider.isAdmin) {
      tabs = ['/refish', '/prebook', '/circulate', '/profile'];
      icons = [
        Icons.change_circle_outlined,
        Icons.bookmark_add_outlined,
        Icons.compare_arrows,
        Icons.person,
      ];
    } else {
      tabs = ['/home', '/fishing', '/community', '/profile'];
      icons = [
        Icons.home,
        Icons.pool,
        Icons.forum,
        Icons.person,
      ];
    }
    final location =
        GoRouter.of(context).routerDelegate.currentConfiguration.uri.toString();
    final currentIndex = _locationToIndex(location);

    return VersionUpdateListener(
      child: Scaffold(
        extendBody: true, // 推荐开启
        backgroundColor: Colors.white,
        body: widget.child,
        bottomNavigationBar: _CustomBottomNavBar(
            currentIndex: currentIndex,
            icons: icons,
            onTap: (index) {
              if (index != currentIndex) {
                context.go(tabs[index]);
              }
            }),
      ),
    );
  }
}

class _CustomBottomNavBar extends StatefulWidget {
  final int currentIndex;
  final List<IconData> icons;
  final ValueChanged<int> onTap;
  const _CustomBottomNavBar(
      {Key? key,
      required this.currentIndex,
      required this.icons,
      required this.onTap})
      : super(key: key);

  @override
  State<_CustomBottomNavBar> createState() => _CustomBottomNavBarState();
}

class _CustomBottomNavBarState extends State<_CustomBottomNavBar>
    with SingleTickerProviderStateMixin {
  late int _selectedIndex;
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _selectedIndex = widget.currentIndex;
    _controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 250));
  }

  @override
  void didUpdateWidget(covariant _CustomBottomNavBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex != _selectedIndex) {
      _controller.forward(from: 0);
      setState(() {
        _selectedIndex = widget.currentIndex;
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<UserProvider>(context);
    const double navHeight = 64;
    const double iconSize = 28;
    const double highlightSize = 48;
    const Color bgColor = Colors.blue;
    const Color unselectedColor = Colors.white70;

    return Container(
      height: navHeight,
      margin: const EdgeInsets.fromLTRB(12, 12, 12, 22),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(navHeight / 2),
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final double width = constraints.maxWidth;
          final double itemWidth = width / 4;
          final double left =
              itemWidth * widget.currentIndex + (itemWidth - highlightSize) / 2;
          return Stack(
            children: [
              AnimatedPositioned(
                duration: const Duration(milliseconds: 300),
                curve: Curves.easeInOut,
                top: (navHeight - highlightSize) / 2,
                left: left,
                child: Container(
                  width: highlightSize,
                  height: highlightSize,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                  ),
                ),
              ),
              Row(
                children: List.generate(4, (index) {
                  final isSelected = widget.currentIndex == index;
                  return Expanded(
                    child: GestureDetector(
                      onTap: () => widget.onTap(index),
                      behavior: HitTestBehavior.opaque,
                      child: SizedBox(
                        height: navHeight,
                        child: Center(
                          child: index == 1 && !provider.isAdmin
                              ? SvgPicture.asset(
                                  'assets/images/logo.svg',
                                  width: iconSize,
                                  height: iconSize,
                                  colorFilter: ColorFilter.mode(
                                    isSelected ? bgColor : unselectedColor,
                                    BlendMode.srcIn,
                                  ),
                                )
                              : Icon(
                                  widget.icons[index],
                                  size: iconSize,
                                  color: isSelected ? bgColor : unselectedColor,
                                ),
                        ),
                      ),
                    ),
                  );
                }),
              ),
            ],
          );
        },
      ),
    );
  }
}
